package com.hyacinth.common.jpql;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.persistence.Query;

import com.hyacinth.common.jpql.reserved.Comparation;

public class Where {
	
	private String alias;
	private StringBuilder statement;
	private Map<String, Object> parameters ;
	private List<Item> items;
	
	Where(String alias) {
		this.alias = alias;
		statement = new StringBuilder();
		parameters = new HashMap<String, Object>();
		items = new ArrayList<Item>();
		
	}
	
	void assign(Query query) {
		Set<String> params = parameters.keySet();
		for(String param : params) {
			query.setParameter(param, parameters.get(param));
		}
	}
	
	@Override
	public String toString() {
		Iterator<Item> it = items.iterator();
		while(it.hasNext()) {
			Item item = it.next();
			String name = "name_"+UUID.randomUUID().toString().replace("-", "");
			statement.append(alias).append(".").append(item.getSign()).append(item.getComparation()).append(":").append(name);
			parameters.put(name, item.getValue());
		}
		return statement.toString();
	}
	
	public Where add(String field, Comparation comparation, Object value) {
		items.add(new Item(field, comparation, value));
		return this;
	}
	
	public Where add(Item item) {
		items.add(item);
		return this;
	}
	
}
